package com.example.asynctaskdemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class NetworkActivity extends AppCompatActivity {

    private static final String TAG = NetworkActivity.class.getSimpleName();
    private static File fileDir;

    private FetchImageAt fetchImageAt;
    private HashMap<String, String> downloadList;
    private Button fetchImageBtn, stopAllBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network);
        findView();
        initView();
        initData();
    }

    private void findView() {
        fetchImageBtn = findViewById(R.id.activity_network_fetch_image_btn);
        stopAllBtn = findViewById(R.id.activity_network_stop_all_btn);
    }

    private void initView() {
        fetchImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchImageAt = new FetchImageAt(downloadList);
                fetchImageAt.execute();
            }
        });

        stopAllBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fetchImageAt != null) {
                    fetchImageAt.cancel(true);
                }
            }
        });
    }

    private void initData() {
        fileDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        downloadList = new HashMap<>();
        downloadList.put("http://imglf6.nosdn0.126.net/img/T2xtRUpvNXdwUVJWQm1QR2s2eklMNTZiOWxuYmxabmI3V1JaYW9KbHJNZ1VvZVVsMWp3WnB3PT0.jpg", "image1.jpg");
        downloadList.put("http://imglf6.nosdn.127.net/img/T2xtRUpvNXdwUVRSeEFvcFhmb2gyMDJmVWtFWWFUck9aYWIvejNKeGVBT0ZOQXJvMnk3Z1l3PT0.jpg", "image2.jpg");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (fetchImageAt != null) {
            fetchImageAt.cancel(true);
        }
    }

    static class FetchImageAt extends AsyncTask {

        private HashMap<String, String> downloadList;

        private FetchImageAt(HashMap<String, String> downloadList) {
            this.downloadList = downloadList;
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            for (Map.Entry<String, String> entry : downloadList.entrySet()) {
                if (!isCancelled()) {
                    String url = entry.getKey();
                    String filePath = entry.getValue();
                    fetchFromInternet(url, filePath);
                }
            }
            return null;
        }
    }

    private static void compressImage(Bitmap bitmap, File downloadFile) {
        try {
            if (downloadFile.createNewFile()) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                try {
                    FileOutputStream fos = new FileOutputStream(downloadFile);
                    try {
                        fos.write(byteArrayOutputStream.toByteArray());
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void fetchFromInternet(String url, String filePath) {
        try {
            File downloadFile = new File(fileDir.getAbsolutePath() + File.separator + filePath);
            if (!downloadFile.getParentFile().exists()) {
                downloadFile.getParentFile().mkdirs();
            }
            if (downloadFile.exists()) {
                downloadFile.delete();
            }
            URL httpUrl = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setRequestMethod("GET");
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = httpURLConnection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                compressImage(bitmap, downloadFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
